package ar.edu.caece.pl.asem.model.impl.treeelements;

import ar.edu.caece.pl.asem.label.LabelGenerator;
import ar.edu.caece.pl.asin.manager.impl.ErrorManager;

public class Si extends AbstractElement {	
	
	public Si (){
		this.label = "IF";
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof Si))
			return false;
		Si other = (Si) obj;
		if (label == null) {
			if (other.label != null)
				return false;
		} else if (!label.equals(other.label))
			return false;
		return true;
	}

	@Override
	public void generateASMCode() {
		
		StringBuffer sb = new StringBuffer();
		if (ErrorManager.debugEnabled) sb.append("; [SI]-Init" + ENTER);
		
		String startLabel = LabelGenerator.getInstance().generateLabel();
		//sb.append(startLabel + ": " + ENTER);		
		
		//Condicion
		if (ErrorManager.debugEnabled) sb.append("; [SI]-Condition" + ENTER);
		this.getChildren().get(0).generateASMCode();
		sb.append(this.getChildren().get(0).code);
		
		//Codigo de adentro del <THEN>
		// TODO: No se xq en el ELSE las lineas de LM están en childrens, mientras que en el SI, están en un solo children
		if (ErrorManager.debugEnabled) sb.append("; [SI]-Then" + ENTER);
		this.getChildren().get(1).generateASMCode();
		sb.append(this.getChildren().get(1).code);
		
		
		if (this.getChildren().size() > 2) {
			// <ELSE>
			if (ErrorManager.debugEnabled) sb.append("; [SI]-Else" + ENTER);
			this.getChildren().get(2).generateASMCode();
			sb.append(TAB + "jmp " + LabelGenerator.getInstance().getActualLabel() + ENTER);
			sb.append(startLabel + ":" + ENTER);
			sb.append(this.getChildren().get(2).code);
		} else {
			sb.append(TAB + "jmp " + startLabel + ENTER);
			sb.append(startLabel + ":" + ENTER);	
		}
		
		if (ErrorManager.debugEnabled) sb.append("; [SI]-End" + ENTER);
		this.code = sb.toString();
	}
	
}
